var root = new Vue({
    el: "#rootDiv",
    data: {
        swaggerResources: [],
        apiDocs: {
            info: {
                title: ""
            }
        }
    },
    methods: {
        submit: submitForm
    },
    filters: {
        formatModel: function (value) {
            return formatModel(value);
        },
        schemaFormat: function (value) {
            if (value) {
                return value.type || value.$ref.replace('#/definitions/', '');
            } else {
                return "";
            }
        }
    }
});

function formatModel(value) {
    try {
        var typeValue = {'string': "", 'int': 0, 'integer': 0, 'object': {}};
        var modelName = value[200].schema.type || value[200].schema.$ref.replace('#/definitions/', '');
        var definitions = root.apiDocs.definitions;
        if (definitions[modelName]) {
            var properties = definitions[modelName].properties;
            var returnValue = {};
            $.each(properties, function (k, v) {
                returnValue[k] = typeValue[v.type]
            });
            return returnValue;
        } else {
            if (modelName === 'string') {
                return '""'
            }
            return typeValue[modelName.trim()];
        }
    }catch (e) {
        console.info(e);
        return "";
    }
}

$(document).ready(function () {
    initSwaggerResources();
    $("input").click(function () {
        $(this).removeClass('input-border-color');
    });
    $("#swaggerResources").change(function () {
        initApi($("#swaggerResources").val());
    });
});

function initSwaggerResources() {
    $.ajax({
        url: "swagger-resources",
        data: "",
        type: "GET",
        async: false,//true为异步，false为同步
        success: function (result) {
            root.swaggerResources = result;
            initApi(result[0].location);
        }
    });
}

function initApi(swaggerResourceLocation) {
    $.ajax({
        url: swaggerResourceLocation,
        data: "",
        type: "GET",
        async: false,//true为异步，false为同步
        success: function (result) {
            result.paths = initPath(result.paths);
            root.apiDocs = result;
        }
    });
}

function initPath(paths) {
    var urlPaths = [];
    $.each(paths, function (url, urlProperties) {
        var urlMap = {};
        urlMap['url'] = url;
        urlMap['type'] = [];
        urlMap['tags'] = [];
        urlMap['consumes'] = [];
        urlMap['description'] = '';
        urlMap['operationId'] = '';
        urlMap['produces'] = [];
        urlMap['responses'] = [];
        urlMap['summary'] = '';
        $.each(urlProperties, function (type, typeProperties) {
            // 请求类型处理
            urlMap['type'].push(type);
            // tag 处理
            var tags = typeProperties.tags;
            $.each(tags, function (tagIndex, tag) {
                if ($.inArray(tag, urlMap['tags']) === -1) {
                    urlMap['tags'].push(tag);
                }
            });

            // 其他参数处理
            urlMap['parameters'] = typeProperties.parameters;
            urlMap['consumes'] = typeProperties.consumes;
            urlMap['description'] = typeProperties.description;
            urlMap['operationId'] = typeProperties.operationId;
            urlMap['produces'] = typeProperties.produces;
            urlMap['responses'] = typeProperties.responses;
            urlMap['summary'] = typeProperties.summary;
        });
        urlPaths.push(urlMap);
    });
    return urlPaths;
}

function submitForm(formId, url) {
    if (formCheck(formId)) {
        var properties = $("#" + formId).serializeArray();
        var type = 'GET';
        var contentType = '*/*';
        $.each(properties, function (index, proper) {
            if (proper.name === 'type') {
                type = proper.value;
            } else if (proper.name === 'contentType') {
                contentType = proper.value;
            }
        });
        headerMap['Accept'] = contentType || "application/json; charset=utf-8";
        $.ajax({
            headers: headerMap,
            url: url,
            data: $("#" + formId).serialize(),
            type: type,
            dataType: 'TEXT',
            async: true,//true为异步，false为同步
            success: function (result) {
                try {
                    $("#rbc-" + formId).jsonViewer(JSON.parse(result), {collapsed: false});
                } catch (e) {
                    console.info(e);
                    $("#rbc-" + formId).text(result);
                } finally {

                }
            }
        });
    }
}

function formCheck(formId) {
    var flag = true;
    var inputDoms = $("#" + formId + " input");
    $.each(inputDoms, function (index, inpuDom) {
        if ($(inpuDom).attr('required')) {
            if (!$(inpuDom).val()) {
                flag = false;
                $(inpuDom).addClass('input-border-color');
                // $(inpuDom).after('<i class="fa fa-times-circle has-error">is not null</i>');
                $(inpuDom).keydown(function () {
                    $(inpuDom).removeClass('input-border-color');
                    // $(inpuDom).next().remove();
                })
            }
        }
    });
    return flag;
}

function checkboxRemoveDisabled(flag, idFlag) {
    var key = $("#" + flag + "key-" + idFlag).val();
    var value = $("#" + flag + "value-" + idFlag).val();
    if (key && value) {
        $("#" + flag + "checkbox-" + idFlag).iCheck('enable')
    } else {
        $("#" + flag + "checkbox-" + idFlag).iCheck('disable')
    }
}